package com.example.activity;

import com.example.activity.dto.ActivityTemplateContext;
import com.example.activity.dto.ext.EvenTemplateExt;
import com.example.activity.repository.InstanceRepository;
import com.example.activity.service.TemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
public abstract class ActivityTemplate {

    @Autowired
    protected ActivityFactory activityFactory;

    @Autowired
    protected TemplateService templateService;

    @Autowired
    protected InstanceRepository instanceRepository;


    // 模板方法
    public final ActivityInstance instance() {
        ActivityInstance activity = createActivityInstance();
        initialize(activity);
        configure(activity);
        validate(activity);
        return activity;
    }

    public final void addAndUpdate(ActivityTemplateContext<EvenTemplateExt> context){
        this.templateValidate("addAndUpdate",context);
        templateService.addAndUpdate(context);
    }
    public final void delete(ActivityTemplateContext<EvenTemplateExt> context){
        this.templateValidate("delete",context);
        templateService.delete(context);
    }
    public final ActivityTemplateContext<EvenTemplateExt> search(ActivityTemplateContext<EvenTemplateExt> context){
        this.templateValidate("search",context);
        return templateService.search(context);
    }

    protected abstract ActivityInstance createActivityInstance();


    protected void initialize(ActivityInstance activity) {
        // 默认初始化逻辑
    }

    protected void configure(ActivityInstance activity) {
        // 默认配置逻辑
    }

    protected void validate(ActivityInstance activity) {
        // 默认验证逻辑
    }

    private void templateValidate(String type,ActivityTemplateContext context) {
        // 默认模版验证逻辑
        switch (type) {
            case "addAndUpdate" -> {
                if (context.getTemplateName() == null) {
                    throw new IllegalArgumentException("templateName is null");
                }
                log.info("templateValidate addAndUpdate");
            }
            case "delete", "search" -> {
                log.info("templateValidate delete|search");
                if (context.getTemplateId() == null) {
                    throw new IllegalArgumentException("TemplateId Can`t be null");
                }
            }
            default -> {
                throw new IllegalArgumentException("type Can`t be null");
            }
        }
    }

    public void save(ActivityInstance instance) {
        instanceRepository.save(instance);
    }

    public ActivityInstance getActivityInstance(String id){
        return instanceRepository.getInstance(id);
    }
}